import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import '../style/utils/responsive.dart';

/// 响应式布局组件
/// 根据屏幕尺寸自动选择合适的布局
class ResponsiveLayout extends StatelessWidget {
  final Widget mobile;
  final Widget? tablet;
  final Widget? desktop;
  final Widget? largeDesktop;

  /// 是否使用淡入淡出动画过渡
  final bool useTransition;

  /// 过渡动画时长
  final Duration transitionDuration;

  const ResponsiveLayout({
    Key? key,
    required this.mobile,
    this.tablet,
    this.desktop,
    this.largeDesktop,
    this.useTransition = true,
    this.transitionDuration = const Duration(milliseconds: 300),
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final widget = _buildResponsiveWidget(context);

    if (useTransition) {
      return AnimatedSwitcher(
        duration: transitionDuration,
        switchInCurve: Curves.easeInOut,
        switchOutCurve: Curves.easeInOut,
        child: Container(
          key: ValueKey(UIResponsive.getDeviceType(context)),
          child: widget,
        ),
      );
    }

    return widget;
  }

  Widget _buildResponsiveWidget(BuildContext context) {
    final deviceType = UIResponsive.getDeviceType(context);

    switch (deviceType) {
      case DeviceType.mobile:
        return mobile;
      case DeviceType.tablet:
        return tablet ?? mobile;
      case DeviceType.desktop:
        return desktop ?? tablet ?? mobile;
      case DeviceType.largeDesktop:
        return largeDesktop ?? desktop ?? tablet ?? mobile;
    }
  }
}

/// 响应式脚手架组件
/// 自动适配不同屏幕尺寸的页面结构
class ResponsiveScaffold extends StatelessWidget {
  final Widget body;
  final PreferredSizeWidget? appBar;
  final Widget? drawer;
  final Widget? endDrawer;
  final Widget? bottomNavigationBar;
  final Widget? floatingActionButton;
  final FloatingActionButtonLocation? floatingActionButtonLocation;
  final Widget? bottomSheet;
  final Color? backgroundColor;
  final bool resizeToAvoidBottomInset;
  final bool extendBody;
  final bool extendBodyBehindAppBar;
  final DragStartBehavior drawerDragStartBehavior;

  /// 桌面端侧边栏
  final Widget? sidebar;

  /// 侧边栏宽度
  final double? sidebarWidth;

  /// 是否在桌面端显示侧边栏
  final bool showSidebarOnDesktop;

  /// 是否在平板端横屏显示侧边栏
  final bool showSidebarOnTabletLandscape;

  const ResponsiveScaffold({
    Key? key,
    required this.body,
    this.appBar,
    this.drawer,
    this.endDrawer,
    this.bottomNavigationBar,
    this.floatingActionButton,
    this.floatingActionButtonLocation,
    this.bottomSheet,
    this.backgroundColor,
    this.resizeToAvoidBottomInset = true,
    this.extendBody = false,
    this.extendBodyBehindAppBar = false,
    this.drawerDragStartBehavior = DragStartBehavior.start,
    this.sidebar,
    this.sidebarWidth,
    this.showSidebarOnDesktop = true,
    this.showSidebarOnTabletLandscape = false,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ResponsiveLayout(
      mobile: _buildMobileScaffold(context),
      tablet: _buildTabletScaffold(context),
      desktop: _buildDesktopScaffold(context),
      largeDesktop: _buildLargeDesktopScaffold(context),
    );
  }

  Widget _buildMobileScaffold(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: body,
      drawer: drawer,
      endDrawer: endDrawer,
      bottomNavigationBar: bottomNavigationBar,
      floatingActionButton: floatingActionButton,
      floatingActionButtonLocation: floatingActionButtonLocation,
      bottomSheet: bottomSheet,
      backgroundColor: backgroundColor,
      resizeToAvoidBottomInset: resizeToAvoidBottomInset,
      extendBody: extendBody,
      extendBodyBehindAppBar: extendBodyBehindAppBar,
      drawerDragStartBehavior: drawerDragStartBehavior,
    );
  }

  Widget _buildTabletScaffold(BuildContext context) {
    final isLandscape = UIResponsive.isLandscape(context);
    final shouldShowSidebar =
        showSidebarOnTabletLandscape && isLandscape && sidebar != null;

    if (shouldShowSidebar) {
      return _buildSidebarLayout(context);
    }

    return _buildMobileScaffold(context);
  }

  Widget _buildDesktopScaffold(BuildContext context) {
    if (showSidebarOnDesktop && sidebar != null) {
      return _buildSidebarLayout(context);
    }

    return Scaffold(
      appBar: appBar,
      body: body,
      endDrawer: endDrawer,
      floatingActionButton: floatingActionButton,
      floatingActionButtonLocation: floatingActionButtonLocation,
      bottomSheet: bottomSheet,
      backgroundColor: backgroundColor,
      resizeToAvoidBottomInset: resizeToAvoidBottomInset,
      extendBody: extendBody,
      extendBodyBehindAppBar: extendBodyBehindAppBar,
    );
  }

  Widget _buildLargeDesktopScaffold(BuildContext context) {
    return _buildDesktopScaffold(context);
  }

  Widget _buildSidebarLayout(BuildContext context) {
    final effectiveSidebarWidth =
        sidebarWidth ?? UIResponsive.getSidebarWidth(context);

    return Scaffold(
      appBar: appBar,
      backgroundColor: backgroundColor,
      resizeToAvoidBottomInset: resizeToAvoidBottomInset,
      extendBody: extendBody,
      extendBodyBehindAppBar: extendBodyBehindAppBar,
      floatingActionButton: floatingActionButton,
      floatingActionButtonLocation: floatingActionButtonLocation,
      bottomSheet: bottomSheet,
      body: Row(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          // 侧边栏
          Container(
            width: effectiveSidebarWidth,
            color: Theme.of(context).drawerTheme.backgroundColor ??
                Theme.of(context).scaffoldBackgroundColor,
            child: sidebar!,
          ),
          // 主内容区域
          Expanded(child: body),
        ],
      ),
    );
  }
}

/// 响应式导航组件
/// 自动在底部导航和侧边栏导航之间切换
class ResponsiveNavigation extends StatelessWidget {
  final List<ResponsiveNavigationItem> items;
  final int currentIndex;
  final ValueChanged<int>? onTap;
  final Color? backgroundColor;
  final Color? selectedItemColor;
  final Color? unselectedItemColor;
  final NavigationType? type;

  const ResponsiveNavigation({
    Key? key,
    required this.items,
    required this.currentIndex,
    this.onTap,
    this.backgroundColor,
    this.selectedItemColor,
    this.unselectedItemColor,
    this.type,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final effectiveType = type ?? UIResponsive.getNavigationType(context);

    switch (effectiveType) {
      case NavigationType.bottom:
        return _buildBottomNavigation(context);
      case NavigationType.sidebar:
        return _buildSidebarNavigation(context);
    }
  }

  Widget _buildBottomNavigation(BuildContext context) {
    return BottomNavigationBar(
      items: items
          .map((item) => BottomNavigationBarItem(
                icon: item.icon,
                activeIcon: item.activeIcon ?? item.icon,
                label: item.label,
                backgroundColor: item.backgroundColor,
                tooltip: item.tooltip,
              ))
          .toList(),
      currentIndex: currentIndex,
      onTap: onTap,
      backgroundColor: backgroundColor,
      selectedItemColor: selectedItemColor,
      unselectedItemColor: unselectedItemColor,
      type: items.length > 3
          ? BottomNavigationBarType.shifting
          : BottomNavigationBarType.fixed,
      showSelectedLabels: true,
      showUnselectedLabels: true,
    );
  }

  Widget _buildSidebarNavigation(BuildContext context) {
    return Container(
      width: UIResponsive.getSidebarWidth(context),
      color: backgroundColor ?? Theme.of(context).drawerTheme.backgroundColor,
      child: Column(
        children: [
          ...items.asMap().entries.map((entry) {
            final index = entry.key;
            final item = entry.value;
            final isSelected = index == currentIndex;

            return ListTile(
              leading: isSelected && item.activeIcon != null
                  ? item.activeIcon!
                  : item.icon,
              title: Text(
                item.label,
                style: TextStyle(
                  color: isSelected ? selectedItemColor : unselectedItemColor,
                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.normal,
                ),
              ),
              selected: isSelected,
              onTap: onTap != null ? () => onTap!(index) : null,
              selectedTileColor: selectedItemColor?.withOpacity(0.1),
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(8),
              ),
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
            );
          }).toList(),
        ],
      ),
    );
  }
}

/// 响应式导航项
class ResponsiveNavigationItem {
  final Widget icon;
  final Widget? activeIcon;
  final String label;
  final Color? backgroundColor;
  final String? tooltip;

  const ResponsiveNavigationItem({
    required this.icon,
    required this.label,
    this.activeIcon,
    this.backgroundColor,
    this.tooltip,
  });
}

/// 响应式容器组件
/// 自动适配内容区域的最大宽度和间距
class ResponsiveContainer extends StatelessWidget {
  final Widget child;
  final double? maxWidth;
  final EdgeInsets? padding;
  final EdgeInsets? margin;
  final AlignmentGeometry? alignment;
  final bool centerContent;

  const ResponsiveContainer({
    Key? key,
    required this.child,
    this.maxWidth,
    this.padding,
    this.margin,
    this.alignment,
    this.centerContent = true,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final effectiveMaxWidth =
        maxWidth ?? UIResponsive.getContentMaxWidth(context);
    final effectivePadding = padding ?? UIResponsive.responsivePadding(context);
    final effectiveMargin = margin ?? EdgeInsets.zero;
    final effectiveAlignment =
        alignment ?? (centerContent ? Alignment.center : null);

    return Container(
      width: double.infinity,
      alignment: effectiveAlignment,
      margin: effectiveMargin,
      child: ConstrainedBox(
        constraints: BoxConstraints(maxWidth: effectiveMaxWidth),
        child: Container(
          padding: effectivePadding,
          child: child,
        ),
      ),
    );
  }
}

/// 响应式侧边栏组件
/// 自动处理侧边栏的显示和隐藏逻辑
class ResponsiveSidebar extends StatelessWidget {
  final Widget child;
  final double? width;
  final Color? backgroundColor;
  final bool showOnMobile;
  final bool showOnTablet;
  final bool showOnDesktop;
  final bool collapsible;
  final bool isCollapsed;
  final VoidCallback? onToggle;
  final Duration animationDuration;

  const ResponsiveSidebar({
    Key? key,
    required this.child,
    this.width,
    this.backgroundColor,
    this.showOnMobile = false,
    this.showOnTablet = true,
    this.showOnDesktop = true,
    this.collapsible = false,
    this.isCollapsed = false,
    this.onToggle,
    this.animationDuration = const Duration(milliseconds: 300),
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final deviceType = UIResponsive.getDeviceType(context);

    // 判断是否应该显示侧边栏
    bool shouldShow = false;
    switch (deviceType) {
      case DeviceType.mobile:
        shouldShow = showOnMobile;
        break;
      case DeviceType.tablet:
        shouldShow = showOnTablet;
        break;
      case DeviceType.desktop:
      case DeviceType.largeDesktop:
        shouldShow = showOnDesktop;
        break;
    }

    if (!shouldShow) {
      return const SizedBox.shrink();
    }

    final effectiveWidth = width ?? UIResponsive.getSidebarWidth(context);
    final collapsedWidth = 64.0; // 折叠后的宽度

    return AnimatedContainer(
      duration: animationDuration,
      width: (collapsible && isCollapsed) ? collapsedWidth : effectiveWidth,
      color: backgroundColor ?? Theme.of(context).drawerTheme.backgroundColor,
      child: Column(
        children: [
          // 折叠按钮
          if (collapsible)
            Container(
              height: 56,
              alignment: Alignment.center,
              child: IconButton(
                icon: Icon(isCollapsed ? Icons.menu : Icons.menu_open),
                onPressed: onToggle,
                tooltip: isCollapsed ? '展开侧边栏' : '收起侧边栏',
              ),
            ),

          // 侧边栏内容
          Expanded(
            child: AnimatedOpacity(
              duration: animationDuration,
              opacity: (collapsible && isCollapsed) ? 0.0 : 1.0,
              child: (collapsible && isCollapsed)
                  ? const SizedBox.shrink()
                  : child,
            ),
          ),
        ],
      ),
    );
  }
}

/// 响应式网格组件
/// 自动根据屏幕尺寸调整网格列数
class ResponsiveGrid extends StatelessWidget {
  final List<Widget> children;
  final int? mobileColumns;
  final int? tabletColumns;
  final int? desktopColumns;
  final int? largeDesktopColumns;
  final double mainAxisSpacing;
  final double crossAxisSpacing;
  final EdgeInsets? padding;
  final double childAspectRatio;

  const ResponsiveGrid({
    Key? key,
    required this.children,
    this.mobileColumns,
    this.tabletColumns,
    this.desktopColumns,
    this.largeDesktopColumns,
    this.mainAxisSpacing = 8.0,
    this.crossAxisSpacing = 8.0,
    this.padding,
    this.childAspectRatio = 1.0,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final columns = UIResponsive.getGridColumns(
      context,
      mobileColumns: mobileColumns ?? 1,
      tabletColumns: tabletColumns ?? 2,
      desktopColumns: desktopColumns ?? 3,
      largeDesktopColumns: largeDesktopColumns ?? 4,
    );

    return Padding(
      padding: padding ?? UIResponsive.responsivePadding(context),
      child: GridView.builder(
        shrinkWrap: true,
        physics: const NeverScrollableScrollPhysics(),
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: columns,
          mainAxisSpacing: mainAxisSpacing,
          crossAxisSpacing: crossAxisSpacing,
          childAspectRatio: childAspectRatio,
        ),
        itemCount: children.length,
        itemBuilder: (context, index) => children[index],
      ),
    );
  }
}
